package com.alibaba.wallstreet.uitls;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.MDC;

public class TraceUtil {

    public static final String TRACE_ID_KEY    = "traceId";
    public static final int    TRACE_ID_LENGTH = 8;

    /**
     * 开始Trace, 默认生成本次Trace的ID(10字符长)并放入MDC.
     */
    public static void beginTrace() {
        String traceId = RandomStringUtils.randomAlphanumeric(TRACE_ID_LENGTH);
        MDC.put(TRACE_ID_KEY, traceId);
    }

    /**
     * 开始Trace, 将traceId放入MDC.
     */
    public static void beginTrace(String traceId) {
        MDC.put(TRACE_ID_KEY, traceId);
    }

    /**
     * 结束一次Trace. 清除traceId.
     */
    public static void endTrace() {
        MDC.remove(TRACE_ID_KEY);
    }

}
